{% extends "app/base_site.html" %}

{% block title %} 录像播放器 {% endblock title %}

{% block stylesheets %}
  {{ block.super }}
    <link rel="stylesheet" href="/static/lib/jquery/daterangepicker/daterangepicker.min.css"/>
      <!-- Ion.RangeSlider -->
  <link href="/static/vendors/normalize-css/normalize.css" rel="stylesheet">
  <link href="/static/vendors/ion.rangeSlider/css/ion.rangeSlider.css?0908" rel="stylesheet">

{% endblock stylesheets %}

{% block content %}
<style>
    video{
        width: 100%;
        height: 100%;
        max-height: 400px;
        background-color: rgba(0,0,00,1.0);
        /*object-fit: fill;*/ /*伸缩*/
        border-radius: 5px;
        /*border: 1px solid #f0f0f0;*/
    }

    video:focus {
        outline: -webkit-focus-ring-color auto 0;
    }

  .timeline-container {
      margin-top: 6px;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: flex-start;
      /*padding: 20px;*/
    }

  .timeline-container > .item-valid {
      width: 100%;
      /*height: 16px;*/
      /*margin: 10px;*/
      /*background-color: #f9f9f9;*/
      /*border-radius: 10px;*/
      /*box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);*/
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
          background-color: #0e62a7;
    }
  .timeline-container > .item-invalid {
      width: 100%;
      /*height: 16px;*/
      /*margin: 10px;*/
      /*background-color: #f9f9f9;*/
      /*border-radius: 10px;*/
      /*box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);*/
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
          background-color: #666;
    }

  .timeline-number {
      line-height: 12px;
      font-size: 12px;
      /*font-weight: bold;*/
      color: #FFFFFF;
    }
    
  /* 美化 ion-rangeSlider 时间进度条 */
  .irs--round .irs-bar {
      background: linear-gradient(to right, #3b82f6 0%, #2563eb 100%);
      height: 6px;
  }
  
  .irs--round .irs-line {
      background: #e5e7eb;
      border-radius: 3px;
      height: 6px;
  }
  
  .irs--round .irs-handle {
      width: 18px;
      height: 18px;
      top: 50%;
      transform: translateY(-50%);
      background: white;
      border: 3px solid #3b82f6;
      box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
  }
  
  .irs--round .irs-handle:hover {
      box-shadow: 0 4px 12px rgba(59, 130, 246, 0.5);
  }
  
  .irs--round .irs-from,
  .irs--round .irs-to,
  .irs--round .irs-single {
      background: #3b82f6;
      color: white;
      font-size: 12px;
      padding: 2px 8px;
      border-radius: 4px;
  }
  
  .irs--round .irs-grid-pol {
      background: #d1d5db;
  }
  
  .irs--round .irs-grid-text {
      color: #6b7280;
      font-size: 11px;
  }
  
  .irs--round .irs-min,
  .irs--round .irs-max {
      background: #f3f4f6;
      color: #6b7280;
      border-radius: 4px;
      padding: 2px 6px;
      font-size: 11px;
  }
  </style>


  <div class="right_col" role="main">
    <div class="">
      <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
          <div class="x_panel">
            <div class="x_title">
                 <h2>录像播放器
                    <span id="top_loading" ><img class="top_loading_img" src="/static/images/load.gif" alt="loading">加载中</span>
                    <span id="top_msg">{{top_msg}}</span>
                 </h2>

                    <div style="float: right; margin-top: 6px; margin-right: 50px;">
                         <input type="text" style="width: 120px;height: 30px;"  id="record_date" class="form-control">
                    </div>

                  <div class="clearfix"></div>
            </div>

            <div class="x_content">

            <div class="col-md-12 col-sm-12 col-xs-12">
                   <video id="video_player" poster="/static/images/player_poster.jpg" muted controls>
                       <!--<source src="#" type="video/mp4">-->
                       Your browser is too old which doesn't support HTML5 video.
                    </video>
              </div>

                 <div class="col-md-12 col-sm-12 col-xs-12">
                     <div id="timeline_div">
                         <!--
                         <input id="timeline" type="text" name="timeline" />
                         -->
                     </div>

                   </div>
                
              <div class="col-md-12 col-sm-12 col-xs-12">
                <div class="timeline-container">
                    <!--
                    <div class="timeline-item">
                      <div class="valid">|</div>
                    </div>
                    -->
                  </div>
              </div>

                <div class="col-md-12 col-sm-12 col-xs-12" style="margin-top: 30px;">
                     <div class="form-horizontal form-label-left" >
                        <div class="form-group">
                          <div class="col-md-4 col-sm-4 col-xs-12">
                             <input type="text"  class="form-control" id="record_video_address" placeholder="当前录像播放地址">
                          </div>
                            <button type="button" onclick="f_downloadRecordVideo()" class="btn btn-dark">下载</button>
                        </div>
                     </div>

                </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
{% endblock content %}

{% block javascripts %}
  {{ block.super }}
   <!-- daterangepicker -->
<script src="/static/vendors/moment/min/moment.min.js"></script>
<script src="/static/lib/jquery/daterangepicker/jquery.daterangepicker.js"></script>
  <!-- Ion.RangeSlider -->
  <script src="/static/vendors/ion.rangeSlider/js/ion.rangeSlider.min.js?0908"></script>
<script>

    let record_code = '{{ code }}';
    let record_day = parseInt('{{ record_day }}');
    let current_date = new Date();
    let current_day = current_date.getDate() //日期，例如1-31,,,

    let eleInputRecordDate = $('#record_date');//选择录像日期
    let eleInputTimelineDiv = $("#timeline_div"); //时间线div
    let eleVideoPlayerJsObj = document.getElementById("video_player")
    let eleVideoPlayerJqueryObj = $("#video_player")
    let eleTimelineContainer = $(".timeline-container");
    let eleInputRecordVideoAddress = $("#record_video_address");
    
    // 连续播放相关变量
    let currentTimestamp = 0; // 当前播放的时间戳
    let isAutoContinue = true; // 是否启用连续播放
    let recordTimelineData = []; // 当前日期的录像时间线数据
    
    // 监听视频播放结束事件，实现连续播放
    eleVideoPlayerJsObj.addEventListener('ended', function() {
        if (isAutoContinue && currentTimestamp > 0) {
            console.log('视频播放结束，准备播放下一个片段...');
            // 下一个片段时间戳：当前时间 + 60秒
            let nextTimestamp = currentTimestamp + 60;
            
            // 获取当前日期的最大时间戳（23:59:59）
            let currentDateObj = new Date(currentTimestamp * 1000);
            let maxTimestamp = new Date(
                currentDateObj.getFullYear(),
                currentDateObj.getMonth(),
                currentDateObj.getDate(),
                23, 59, 59
            ).valueOf() / 1000;
            
            // 如果下一个时间戳没有超出当天，则继续播放
            if (nextTimestamp <= maxTimestamp) {
                console.log('播放下一个片段:', new Date(nextTimestamp * 1000));
                f_openRecordFilename(nextTimestamp);
            } else {
                console.log('已达当天最后一个片段，停止播放');
            }
        }
    });

    eleInputRecordDate.val(current_date.toLocaleDateString())

    function f_downloadRecordVideo() {
        let url = eleInputRecordVideoAddress.val().trim();
        if(url.startsWith("/storage/openAccess?filename=")){
            window.open(url);
        }else{
               myToast2025("录像播放地址不正确！","error");
        }
    }
    function f_openRecordFilename(timestamp){
        eleInputRecordVideoAddress.val("");
        
        // 保存当前时间戳，用于连续播放
        currentTimestamp = timestamp;

        $.ajax({
           url: "/streamRecord/openRecordFilename",
           type: "get",
           async: true,
           data: {
               "code":record_code,
               "timestamp": timestamp
           },
           timeout: 0,
           error: function () {
                myToast2025("网络异常，请确定网络正常！","error");
           },
           success: function (res) {
               if(1000 === res.code){
                   //此前的播放中断

                   try {
                       eleVideoPlayerJsObj.pause();
                   }catch (e) {
                       console.log("eleVideoPlayerJsObj.pause():",e)
                   }

                   try {
                       eleVideoPlayerJqueryObj.removeAttr("src");
                       eleVideoPlayerJqueryObj.load();
                   }catch (e) {
                       console.log("eleVideoPlayerJqueryObj.removeAttr():",e)
                   }

                   let info = res.info;
                   let filename = info.filename

                   let url = "/storage/openAccess?filename="+filename;

                   eleInputRecordVideoAddress.val(url);

                   eleVideoPlayerJsObj.src = url;
                   eleVideoPlayerJsObj.play();

               }else{
                   try {
                       eleVideoPlayerJsObj.pause();
                   }catch (e) {
                       console.log("eleVideoPlayerJsObj.pause():",e)
                   }

                   try {
                       eleVideoPlayerJqueryObj.removeAttr("src");
                       eleVideoPlayerJqueryObj.load();
                   }catch (e) {
                       console.log("eleVideoPlayerJqueryObj.removeAttr():",e)
                   }
                   myToast2025(res.msg,"error");
                   
                   // 如果当前片段不存在，尝试播放下一个片段
                   if (isAutoContinue && currentTimestamp > 0) {
                       console.log('当前片段不存在，尝试下一个...');
                       let nextTimestamp = currentTimestamp + 60;
                       let currentDateObj = new Date(currentTimestamp * 1000);
                       let maxTimestamp = new Date(
                           currentDateObj.getFullYear(),
                           currentDateObj.getMonth(),
                           currentDateObj.getDate(),
                           23, 59, 59
                       ).valueOf() / 1000;
                       
                       if (nextTimestamp <= maxTimestamp) {
                           setTimeout(function() {
                               f_openRecordFilename(nextTimestamp);
                           }, 500); // 稍微延迟后再试
                       }
                   }
               }
           }
        });
        
    }
    function f_openRecordTimeline(date) {
       try {
            eleVideoPlayerJsObj.pause();
            //eleVideoPlayerJsObj.currentTime = 0;
            eleVideoPlayerJqueryObj.removeAttr("src");
            eleVideoPlayerJqueryObj.load();
       }catch (e) {
           console.log("f_openRecordTimeline error:",e)
       }
       
       // 重置当前时间戳
       currentTimestamp = 0;

        let timestamp = parseInt(date.valueOf() / 1000);//秒级时间戳
        $.ajax({
           url: "/streamRecord/openRecordTimeline",
           type: "get",
           async: true,
           data: {
               "code":record_code,
               "timestamp": timestamp
           },
           timeout: 0,
           error: function () {
                myToast2025("网络异常，请确定网络正常！","error");
           },
           success: function (res) {

               if(1000 === res.code){
                    let data = res.data;
                    // 保存录像时间线数据
                    recordTimelineData = data;
                    
                    let html = "";
                    for (let i = 0; i < data.length; i++) {
                        let record = data[i].record;
                        if(record === 1){
                            html += "<div class=\"item-valid\">";
                            html += "<div class=\"timeline-number\">|</div>";
                            html += "</div>";
                        }else{
                            html += "<div class=\"item-invalid\">";
                            html += "<div class=\"timeline-number\">|</div>";
                            html += "</div>";
                        }
                    }

                    eleTimelineContainer.html(html);

                    let date_year = date.getFullYear()
                    let date_month = date.getMonth() //数值比正常月份减1
                    let date_day = date.getDate() //日期，例如1-31,,,
                    let date_hour = date.getHours()
                    let date_minute = date.getMinutes()

                    eleInputTimelineDiv.html("<input id=\"timeline\" type=\"text\" name=\"\" />")
                    let eleInputTimeline = $("#timeline"); //时间线

                    //if(date_hour ===0 && date_minute === 0){
                    //    date_hour = 8;
                    //}

                    eleInputTimeline.ionRangeSlider({
                        skin: "round", //常用选项 flat,round,big
                        //type: "double",
                        min: (new Date(date_year, date_month, date_day, 0, 0)).valueOf(),
                        max: (new Date(date_year, date_month, date_day, 23, 59)).valueOf(),
                        from: (new Date(date_year, date_month, date_day, date_hour,date_minute)).valueOf(),
                         //to: dateToTS(new Date(year, 10, 23)),
                        step: 1,            // default 1 (set step)
                        grid: true,         // default false (enable grid)
                        grid_num: 4,        // default 4 (set number of grid cells)
                        prettify: tsToDate,
                        onStart: function (data) {
                            // fired then range slider is ready
                            //console.log("onStart:",typeof data,data)

                        },
                        onChange: function (data) {
                            // fired on every range slider update
                             //console.log("onChange:",typeof data,data)
                        },
                        onFinish: function (data) {
                            // fired on pointer release
                             //console.log("onFinish:",typeof data,data)
                             let timestamp = parseInt(data.from / 1000);//秒级时间戳
                             f_openRecordFilename(timestamp);
                        },
                        onUpdate: function (data) {
                            // fired on changing slider with Update method
                             //console.log("onUpdate:",typeof data,data)
                        }
                    });

               }else{
                    myToast2025(res.msg,"error");
               }
           }
        });

        
    }
    function tsToDate (timestamp) {
        let d = new Date(timestamp);
        //toLocaleDateString参考文档： https://www.cnblogs.com/bokemoqi/p/17656900.html

        //en-US,zh-CN
        return d.toLocaleDateString("zh-CN", {
            //year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: 'numeric',
            minute: 'numeric',
            //second: 'numeric',
        });
    }
    eleInputRecordDate.dateRangePicker({
        language:'cn',//cn,en
        autoClose: true,
        singleDate : true,
        showShortcuts: false,
        singleMonth: true,
        beforeShowDay: function(time)
        {
            let cost_ms = current_date - time;
            let cost_day = cost_ms / (1000 * 60 * 60 * 24);//距离当前时间已经花费的天数，float类型
            // time.getDate(), time.getDay()
            let valid = false;
            if (cost_day >=0 && cost_day <= record_day){
                valid = true;
            }
            //valid = !(time.getDay() == 0 || time.getDay() == 6);  //disable saturday and sunday
            let tip = valid ? '' : '未录像';
            return [valid,'',tip];
        }
    }).bind('datepicker-change',function(event,obj)
        {
            //console.log(typeof event,event)
            //console.log(typeof obj,obj)
            //console.log(typeof obj.date1,obj.date1)
            f_openRecordTimeline(obj.date1);
        });

    f_openRecordTimeline(current_date);

</script>

{% endblock javascripts %}
